#include "Wizard.h"

#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QDir>
#include <QFileDialog>
#include <QDebug>

#include "data/Config.h"

Wizard::Wizard(bool firstTime, QWidget *parent) :
    QWizard(parent),
    m_firstTime(firstTime)
{

    setWizardStyle ( QWizard::ModernStyle );
    setOption ( QWizard::NoBackButtonOnStartPage, true);
    setMinimumSize(600,490);
    setPage(Page_Intro, createIntroPage());
    setPage(Page_Fb, createConnectPage());
    setPage(Page_FbError, createFbErrorPage());
    setPage(Page_SteamError, createSteamErrorPage());
    setPage(Page_Steam, createSteamPage());
    setPage(Page_SaveDir, createSaveDirPage());
    setPage(Page_Conclusion, createConclusionPage());

}

QWizardPage* Wizard::createIntroPage()
{
    QWizardPage *qwp = new QWizardPage();
    qwp->setTitle("Welcome!");
    QLabel *l;
    if (m_firstTime)
    {
        l = new QLabel("Since this is your first time using Steam2Fb "
                       "we'll need to get your Steam information and "
                       "you'll need to log into Facebook and authorize "
                       "this application to access your account. "
                       "Neither your email address or password are saved by this application.<br><br>"
                       " Click 'Next' below to get started!");
    }
    else
    {
        l = new QLabel("It would appear that the session provided by Facebook through "
                       "their Facebook Connect API has become invalid (unfortunately "
                       "this happens occasionally). In order to continue using this"
                       "application you must log into Facebook again.<br><br> "
                       "Click 'Next' below to log back into Facebook via Facebook Connect");
    }

    l->setWordWrap(true);
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(l);
    qwp->setLayout(layout);
    //QPixmap pm;
    //pm.load(":/uiImages/signGuy.jpg");

    //qwp->setPixmap(QWizard::WatermarkPixmap, pm);
    return qwp;



}

QWizardPage* Wizard::createConnectPage()
{
    // create FB connect page
    ConnectPage *cp = new ConnectPage();

    return cp;
}

QWizardPage* Wizard::createSteamPage()
{
    SteamPage *sp = new SteamPage();
    return sp;
}

QWizardPage* Wizard::createFbErrorPage()
{
    FbErrorPage *ep = new FbErrorPage();
    return ep;
}

QWizardPage* Wizard::createSteamErrorPage()
{
    SteamErrorPage *ep = new SteamErrorPage();
    return ep;
}

QWizardPage* Wizard::createSaveDirPage()
{
    SaveDirPage *sdp = new SaveDirPage();
    return sdp;
}

QWizardPage* Wizard::createConclusionPage()
{
    ConclusionPage *cp = new ConclusionPage();
    return cp;
}

WebView::WebView(QWidget *parent) :
        QWebView(parent)
{
    connect(this,SIGNAL(loadFinished(bool)),
            this, SLOT(loadFinished()));
}

void WebView::loadFinished()
{
    if (page()->findText("Success"))
    {
        QString str = url().toString();
        qDebug() << str;

        QRegExp rx("access_token=(.*)");
        if (rx.indexIn(str) != -1)
        {
            Config::getInstance()->setOAuthToken(rx.cap(1));
            qDebug() << rx.cap(1);
            emit authReceived();
        }
        else
        {
            emit authFailed();
        }

    }
    else if (page()->findText("Failed"))
    {
        emit authFailed();
    }



}

ConnectPage::ConnectPage(QWidget *parent) :
        QWizardPage(parent),
        m_isComplete(false),
        m_gotAuth(false)
{

    m_view = new WebView();

    m_facebookUrl = "https://graph.facebook.com/oauth/authorize?"
                    "client_id=123417664335811&"
                    "redirect_uri=http://www.facebook.com/connect/login_success.html&"
                    "type=user_agent&"
                    "scope=publish_stream,offline_access&"
                    "display=popup";
    connect(m_view, SIGNAL(authReceived()),
            this, SLOT(gotAuth()));
    connect(m_view, SIGNAL(authFailed()),
            this, SLOT(gotFailed()));

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(m_view);
    setLayout(layout);


}

void ConnectPage::initializePage()
{
    QUrl url(m_facebookUrl);
    m_view->load(url);
}

void ConnectPage::gotAuth()
{
    //initializePage();
    m_isComplete = true;
    m_gotAuth = true;
    emit completeChanged();
    ((QPushButton*)this->wizard()->button(QWizard::NextButton))->click();
}

void ConnectPage::gotFailed()
{
    initializePage();

    m_isComplete = true;
    emit completeChanged();
    ((QPushButton*)this->wizard()->button(QWizard::NextButton))->click();
}

bool ConnectPage::isComplete() const {
    return m_isComplete;
}



int ConnectPage::nextId() const {
    if (m_gotAuth)
        return Wizard::Page_Steam;
    else
        return Wizard::Page_FbError;
}

SteamPage::SteamPage(QWidget *parent) :
        QWizardPage(parent),
        m_isComplete(false),
        m_steamVerified(false)
{
    setTitle("Steam Community");

    QLabel *l = new QLabel("Please enter your custom Steam Community name or Steam Id "
                           "used to access your Steam profile. Please note that for this "
                           "application to work, your Steam profile must be public.<BR>");
    l->setWordWrap(true);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(l);

    QHBoxLayout *hLayout = new QHBoxLayout();
    l = new QLabel("http://steamcommunity.com/id/");
    hLayout->addWidget(l);
    m_steamIdInput = new QLineEdit();

    connect(m_steamIdInput, SIGNAL(textChanged(QString)),
            this, SLOT(inputEntered(QString)));

    hLayout->addWidget(m_steamIdInput);
    hLayout->addStretch();
    layout->addLayout(hLayout);
    m_verifyButton = new QPushButton();
    m_verifyButton->setText("Verify");
    m_verifyButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    m_verifyButton->setEnabled(false);

    connect(m_verifyButton, SIGNAL(clicked()),
            this, SLOT(verifyPressed()));

    hLayout->addWidget(m_verifyButton,1,Qt::AlignLeft);

    setLayout(layout);

}

void SteamPage::inputEntered(QString input)
{
    if (input != "")
        m_verifyButton->setEnabled(true);
    else
        m_verifyButton->setEnabled(false);
}

void SteamPage::verifyPressed()
{

    QNetworkAccessManager *nam = new QNetworkAccessManager(this);

    connect(nam, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(steamReply(QNetworkReply*)));

    QNetworkRequest nr;
    nr.setUrl(QUrl("http://steamcommunity.com/id/" +
                   m_steamIdInput->text() +
                   "?xml=1"));
    nam->get(nr);


}

void SteamPage::steamReply(QNetworkReply *reply)
{

    m_isComplete = true;

    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray ba = reply->readAll();
        if (!ba.contains("error"))
        {
            m_steamVerified = true;
            Config::getInstance()->setSteamId(m_steamIdInput->text());
        }
        else
        {
            m_steamIdInput->setText("");
        }
        //qDebug() << ba;


    }
    else
    {
        qDebug() << "Error retrieving Steam page: "
                << reply->errorString();

    }

    reply->deleteLater();

    emit completeChanged();

    ((QPushButton*)this->wizard()->button(QWizard::NextButton))->click();

    if (!m_steamVerified)
        m_isComplete = false;
}


bool SteamPage::isComplete() const
{
    return m_isComplete;

}

int SteamPage::nextId() const
{
    if (m_steamVerified)
        return Wizard::Page_SaveDir;
    else
        return Wizard::Page_SteamError;
}

SaveDirPage::SaveDirPage(QWidget *parent) :
        QWizardPage(parent),
        m_isComplete(false)
{
    m_path = QDir::homePath();
    Config::getInstance()->setSaveDir(m_path);

    setTitle("Data Directory");

    QLabel *l = new QLabel("Choose the directory where "
                             " Steam2Fb will store your Steam "
                             "data<BR>");

    l->setWordWrap(true);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(l);


    QHBoxLayout *hLayout = new QHBoxLayout();
    m_pathLabel = new QLabel("<b>Currently:</b> " +  m_path);
    hLayout->addWidget(m_pathLabel);
    m_chooseButton = new QPushButton("Change");

    connect(m_chooseButton, SIGNAL(clicked()),
            this, SLOT(choosePressed()));

    hLayout->addWidget(m_chooseButton,1,Qt::AlignLeft);
    layout->addLayout(hLayout);
    setLayout(layout);




}

bool SaveDirPage::isComplete() const
{
    return true;
}

void SaveDirPage::choosePressed()
{

    m_path = QFileDialog::getExistingDirectory(this, tr("Choose Directory"),
                                                 m_path,
                                                 QFileDialog::ShowDirsOnly
                                                 | QFileDialog::DontResolveSymlinks);

    m_pathLabel->setText("<b>Currently: </b>" + m_path);
    Config::getInstance()->setSaveDir(m_path);

}

int SaveDirPage::nextId() const
{
    return Wizard::Page_Conclusion;
}

ConclusionPage::ConclusionPage(QWidget *parent) :
        QWizardPage(parent)
{
    setTitle("Authorized!");


    QLabel *l = new QLabel("All set! This application can now access your Facebook and Steam page.<br><br>"
                           "Click 'Finish' below to start the application.");
    l->setWordWrap(true);
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(l);
    setLayout(layout);

    setFinalPage(true);
}

int ConclusionPage::nextId() const {
    return -1;
}



FbErrorPage::FbErrorPage(QWidget *parent) :
        QWizardPage(parent)
{
    //QPixmap pm;
    //pm.load(":/uiImages/thumbsDown3.jpg");
    //setPixmap(QWizard::WatermarkPixmap, pm);
    setTitle("Ruh Roh!");

    QLabel *l = new QLabel("Unfortunately your Facebook Connect session didn't go as planned.<br><br>"
                "Please go back and try again. Please note that this application requires"
                " publish and offline access to function.");

    l->setWordWrap(true);
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(l);
    setLayout(layout);
}

bool FbErrorPage::isComplete() const
{
    return false;
}

SteamErrorPage::SteamErrorPage(QWidget *parent) :
        QWizardPage(parent)
{
    //QPixmap pm;
    //pm.load(":/uiImages/thumbsDown3.jpg");
    //setPixmap(QWizard::WatermarkPixmap, pm);
    setTitle("Ruh Roh!");

    QLabel *l = new QLabel("Unfortunately we couldn't find the Steam "
                           "Community page you specified. Please go "
                           "back and try again.");

    l->setWordWrap(true);
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(l);
    setLayout(layout);
}

bool SteamErrorPage::isComplete() const
{
    return false;
}
